<!-- eslint-disable indent -->
<template>
  <div class="relate-form">
    <CpForm
      ref="searchForm"
      :model="searchModel"
      :items="searchFields"
      :rules="rules"
      :inline="inline"
      :class="collapse ? 'relate-form-input-up' : 'relate-form-input-down'"
      :style="{
        '--colNum': colNum,
        '--colNum2': colNum2,
        'min-height': styleHeights
      }"
      :label-width="labelWidth || '110px'"
      label-position="top"
    ></CpForm>
    <div v-if="hasBtn" :class="[calclass, 'relate-form-reviewbtn']">
      <c-button class="search" type="primary" @click="doSearch">
        查询
      </c-button>
      <c-button class="reset" @click="doReset">
        重置
      </c-button>
      <c-button
        v-if="drawerModel || searchFields.length > colNum"
        class="collapse"
        :icon="collapse ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
        @click="doCollapse"
      ></c-button>
    </div>
    <div v-if="collapse" class="relate-form-mongolia"></div>
    <div class="relate-form-content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
import CpForm from '@/components/searchForm'
import { requestCommon } from '@/api/common'
export default {
  name: 'CateForm',
  components: { CpForm },
  props: {
    drawerModel: {
      type: Boolean,
      default: () => false
    },
    items: {
      type: Array,
      default: () => {
        return []
      }
    },
    searchModelAdd: {
      type: Object,
      default: () => {
        return {}
      }
    },
    inline: {
      type: Boolean,
      default: false
    },
    hasBtn: {
      type: Boolean,
      default: true
    },
    labelWidth: {
      type: String,
      default: '90'
    },
    rules: {
      type: Object,
      default: () => {
        return {}
      }
    },
    colNum: {
      type: Number,
      default: 6
    }
  },
  data () {
    return {
      suffix: '_map',
      list: {},
      searchModel: {
        ...this.searchModelAdd
      },
      searchFields: [],
      fieldMap: {},
      collapse: false,
      colNums: 0,
      colNum2: 0,
      styleHeights: ''
    }
  },
  computed: {
    calclass () {
      const length = this.searchFields.length
      const colNum = this.colNum
      // console.log(length)
      let className = 'relate-form-reviewbtn-1'
      if (length > 0 && length < colNum - 1) {
        className = 'relate-form-reviewbtn-1'
      } else if (length > colNum - 1 && length < 2 * colNum && !this.collapse) {
        className = 'relate-form-reviewbtn-2'
      } else if (length > colNum - 1 && length < 2 * colNum && this.collapse) {
        className = 'relate-form-reviewbtn-3'
      } else if (
        length > 2 * colNum - 1 &&
        length < 3 * colNum &&
        !this.collapse
      ) {
        className = 'relate-form-reviewbtn-2'
      } else if (
        length > 2 * colNum - 1 &&
        length < 3 * colNum &&
        this.collapse
      ) {
        className = 'relate-form-reviewbtn-4'
      } else if (
        length > 3 * colNum - 1 &&
        length < 4 * colNum &&
        !this.collapse
      ) {
        className = 'relate-form-reviewbtn-2'
      } else if (
        length > 3 * colNum - 1 &&
        length < 4 * colNum + 3 &&
        this.collapse
      ) {
        className = 'relate-form-reviewbtn-5'
      } else {
        className = 'relate-form-reviewbtn-1'
      }
      return className
    }
  },
  watch: {
    items () {
      if (this.drawerModel) {
        this.init()
        this.initDom()
      }
    },
    collapse: {
      // eslint-disable-next-line space-before-function-paren
      handler: function (v) {
        if (v) {
          const length = this.searchFields.length
          const colNum = this.colNum
          if (length > 0 && length % colNum === 0) {
            // 判断length是colnum的倍数
            this.styleHeights = this.colNum * 82 + 72 + 'px'
            console.log(this.styleHeights)
          } else {
          }
        } else {
          this.styleHeights = ''
        }
      },
      deep: true
    }
  },
  created () {
    this.init()
  },
  mounted () {
    const colNum1 = (this.colNum - 1) * 16 + 'px'
    this.colNum2 = `calc((100% - ${colNum1}) / ${this.colNum})`
    this.initDom()
  },
  methods: {
    clear (value) {
      // console.log('resetValue',this.searchModel)
      if (value) {
        Object.assign(this.searchModel, value)
      } else {
        // this.searchModel = {...this.searchModelAdd}
        this.$refs['searchForm'].resetFields()
      }
    },
    init () {
      this.items.forEach((item) => {
        this.fieldMap[item.prop] = item
        item.xStore &&
          Object.prototype.toString.call(item.xStore) === '[object Function]' &&
          (item.xStore = item.xStore.bind(this))
        //  Object.prototype.toString.call(item.xStore) === "[object Function]"判断当xStore类型为Function
        // 时，再去bind(this),而不至于在item.prop为其它类型时去使用xStore而页面报错
        // console.log('itemitemitem',item);
        const _build = item.build
        if (_build && _build.type === 'static' && _build.url) {
          this.require(_build, item).then(() => {
            if (_build.child) {
              const child = this.fieldMap[_build.child]
              this.$watch(`searchModel.${item.prop}`, (newV) => {
                this.searchModel[`${item.build.child}`] = ''
                if (newV === '') {
                  // reset
                  this.list[child.build.xStore] = []
                } else {
                  const params = {}
                  params[child.build.params] =
                    this[`${item.prop}${this.suffix}`][newV]
                  this.require(child.build, child, params)
                }
                this.$emit('modelChange', item.prop, newV)
              })
            }
          })
        } else {
          this.$watch(`searchModel.${item.prop}`, (newV) => {
            this.$emit('modelChange', item.prop, newV)
          })
        }
      })
      this.searchFields = this.items
    },
    require (build, filed, params) {
      return requestCommon({
        url: build.url,
        method: 'get',
        params
      }).then((res) => {
        if (res.success) {
          const mapKey = `${filed.prop}${this.suffix}`
          this[mapKey] = {}
          const finalData = res.data.map((item) => {
            this[mapKey][item[build.name]] = item[build.value]
            return {
              value: item[build.value],
              label: item[build.name]
            }
          })
          // console.log('finalDatafinalData', finalData)
          this.$set(this.list, build.xStore, finalData)
        }
      })
    },
    getData () {
      const res = {}
      for (const key in this.searchModel) {
        // if (this.searchModel[key]) {
        //   const _map = `${key}${this.suffix}`
        //   if (this[_map]) {
        //     console.log(this.searchModel[key])
        //     res[key] = this[_map][key]
        //     console.log('key:::::::', key)
        //     console.log('res[key]:::::::', res[key])
        //     console.log('_map:::::::', _map)
        //     console.log('this[_map]:::::::', this[_map])
        //     console.log('this.searchModel[key]:::::::', this.searchModel[key])
        //   } else {
        //     res[key] = this.searchModel[key]
        //   }
        // } else {
        //   res[key] = this.searchModel[key]
        // }
        res[key] = this.searchModel[key]
      }
      // console.log(this.searchModel)
      return res
    },
    doSearch () {
      if (this.collapse) {
        this.collapse = false
      }
      this.$emit('searchFilter', this.getData())
    },
    doReset () {
      if (this.collapse) {
        this.collapse = false
      }
      for (const k in this.searchModel) {
        this.searchModel[k] = null
      }
      // this.$emit('searchFilter', this.getData())
      this.$emit('clear', this.getData())
    },
    doCollapse () {
      this.collapse = !this.collapse
      if (this.drawerModel) {
        this.$emit('collapse', this.collapse)
      }
    },
    validate () {
      return new Promise((resolve, reject) => {
        this.$refs['searchForm'].validate((valid) => {
          if (valid) {
            resolve(valid)
          } else {
            reject(valid)
          }
        })
      })
    },
    getFilterParams () {
      return this.getData()
    },
    resetFields () {
      //
      this.clear()
    },
    initDom () {
      for (let i = 0; i < this.colNum; i++) {
        this.$nextTick(() => {
          if (
            document.querySelector(
              `.fields-box-item:nth-child(${(i + 1) * this.colNum})`
            )
          ) {
            document.querySelector(
              `.fields-box-item:nth-child(${(i + 1) * this.colNum})`
            ).style.margin = 0
          }
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
$--widths: var(--colNum2);
$--widthsns: 24px;
.relate-form {
  height: 100%;
  position: relative;
  background: #fff;
  overflow-y: scroll;
  &-input-down,
  &-input-up {
    height: 82px;
    overflow: hidden;
    padding: $--widthsns;
    :deep(.fields-box) {
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start; // 替代原先的space-between布局方式
      .fields-box-item {
        flex: 1;
        margin: 0 16px 0 0;
        width: $--widths; // 这里的80px = (分布个数colNum-1)*间隙16px, 可以根据实际的分布个数和间隙区调整
        min-width: $--widths; // 加入这两个后每个item的宽度就生效了
        max-width: $--widths; // 加入这两个后每个item的宽度就生效了
        .el-form-item {
          .el-form-item__label {
            line-height: 20px;
          }
          .el-form-item__content {
            .el-select,
            .el-radio-group {
              width: 100%;
            }
            .el-input__inner {
              height: 32px;
              line-height: 32px;
              // border-radius: 0;
            }
            .el-date-editor .el-range__icon,
            .el-date-editor .el-range__close-icon,
            .el-date-editor .el-range-separator {
              line-height: 25px;
              padding: 0 0 0 2px;
            }
            .el-date-editor .el-range__close-icon {
              width: 16px;
            }
            .el-date-editor--datetimerange.el-input,
            .el-date-editor--datetimerange.el-input__inner,
            .el-date-editor.el-input,
            .el-date-editor.el-input__inner {
              width: 100%;
            }
            .el-radio {
              margin-right: 25px;
            }
          }
        }
      }
    }
  }
  &-input-up {
    height: auto;
    position: absolute;
    width: 100%;
    z-index: 400;
    background: #fff;
  }
  &-reviewbtn {
    //搜索重制
    text-align: right;
    font-size: 12px;
    line-height: 32px;
    .search,
    .reset,
    .collapse {
      width: 60px;
      height: 32px;
      text-align: center;
      padding: 5px 16px;
      // border-radius: 0;
    }
    .search {
      background: #3786fd;
      color: #fff;
    }
    .collapse {
      width: 32px;
      padding: 5px 9px;
    }
    span {
      font-weight: 500;
    }
  }
  &-reviewbtn-1,
  &-reviewbtn-2,
  &-reviewbtn-3,
  &-reviewbtn-4,
  &-reviewbtn-5 {
    position: absolute;
    top: 2 * $--widthsns;
    right: $--widthsns;
    z-index: 600;
  }
  &-reviewbtn-2 {
    top: 94px;
  }
  &-reviewbtn-3 {
    top: 129px;
  }
  &-reviewbtn-4 {
    top: 212px;
  }
  &-reviewbtn-5 {
    top: 294px;
  }
  &-mongolia {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.6);
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 100;
  }
  &-content {
    position: absolute;
    top: 94px;
    right: $--widthsns;
    left: $--widthsns;
    // z-index: 1;
  }
}
</style>
